#!/user/bin/env python3
# -*- coding: utf-8 -*-
#-- anth bluedolphi ---
import sys

import requests
from fake_useragent import UserAgent
from pip._vendor.requests.structures import CaseInsensitiveDict
import base64
import httpx

class BaseHttpUtil:

    userAgent = UserAgent()
    AGENT_STRING = userAgent.random
    pageSize = 30

    def __init__(self,host,AGENT_STRING=None,proxies=None):
        self.host = host;
        if AGENT_STRING is not None:
            self.AGENT_STRING = AGENT_STRING;
        self.proxies = proxies
        self.http = requests.session()
        pass

    def getTotalPages(self,rows,pageSize):
        totalPage = 0;
        if rows>1:
            totalPage = rows//pageSize
            if rows%pageSize>0:
                totalPage+=1

        return totalPage;



    def view_bar(self,title,num, total):
        if total==0:
            return
        rate = num / total  # 得到现在的比率，0<rate<1
        rate_num = int(rate * 100)  # 将比率百分化，0<rate_num<100
        r = '\r%s[%s%s]' % (title,">" *int(num*100/total), " " * (100 - int(num*100/total)))  # 进度条封装
        sys.stdout.write(r)  # 显示进度条
        sys.stdout.write(' '+str(rate_num) + '%')  # 显示进度百分比
        sys.stdout.flush()  # 使输出变得平滑

    def request(self, method, url, params=None, data=None, files=None, headers=None, ajax=False, stream=None):
        _headers = CaseInsensitiveDict([
            ('Accept', 'text/html,image/webp,image/apng,*/*;q=0.8'),
            ('Accept-Encoding', 'gzip, deflate'),
            ('Accept-Language', 'en-US,en;q=0.8'),
            ('Accept-Charset', 'utf-8;q=0.7,*;q=0.7'),
            ('Cache-Control', 'no-cache'),
            ('Connection', 'keep-alive'),
            ('Host', self.host),
            ('User-Agent', self.AGENT_STRING)])
        if method.upper() == 'POST':
            _headers.update([('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')])
        if ajax:
            _headers.update([('Accept', 'application/json')])
            csrftoken = self.http.cookies.get('csrftoken')
            if csrftoken:
                _headers.update([('X-CSRFToken', csrftoken)])
            _headers.update([('X-Requested-With', 'XMLHttpRequest')])
        if headers:
            _headers.update(headers)
        response = self.http.request(method, url, params=params, data=data, headers=_headers,
                                     files=files, timeout=240, proxies=self.proxies, stream=stream)
        response.raise_for_status()
        return response


    def get(self, url, params=None, headers=None, ajax=False, stream=None):
        return self.request('GET', url=url, params=params, headers=headers, ajax=ajax, stream=stream)

    def post(self, url, data=None, files=None, headers=None, ajax=False, stream=None):
        return self.request('POST', url=url, data=data, files=files, headers=headers, ajax=ajax, stream=stream)

    def head(self,url, data=None, files=None, headers=None, ajax=False, stream=None):
        return  self.request("HEAD",url, data=None, files=None, headers=None, ajax=False, stream=None)


    def saveBase64Image(self,url,fileName="imageToSave.png"):
        img = base64.urlsafe_b64decode(url + '=' * (4 - len(url) % 4))
        fh = open(fileName, "wb")
        fh.write(img)
        fh.close()


